package com.ruoyi.gateway.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.gateway.config.properties.CaptchaProperties;
import com.ruoyi.gateway.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码过滤器
 *
 * @author ruoyi
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
{
    private final static String[] VALIDATE_URL = new String[] { "/auth/login", "/auth/register" };
    private final static String VALIDATE_LOGIN_URL ="/auth/login";
    private final static String VALIDATE_REGISTER_URL ="/auth/register";
    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private CaptchaProperties captchaProperties;

    private static final String CODE = "code";

    private static final String UUID = "uuid";
    /**
     * 验证模式:短信验证码
     */
    private static final String VERIFY_MODE = "verifyMode";

    /**
     * 验证模式：密码验证码
     */
    private static final String PASSWORD_CODEMODE ="passwordMode";
    /**
     * 跳过验证码开关
     */
    private static final String SKIP_VERIFICATION_CODE = "skipVerificationCode";
    /**
     * 跳过验证码标志
     */
    public final static String SKIP_VERIFICATION_CODE_FLAG = "e9d0vuq77lrevlpgvf8qm7l24jhsvi";
    @Override
    public GatewayFilter apply(Object config)
    {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            // 非登录/注册请求或验证码关闭，不处理
            if (!StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) || !captchaProperties.getEnabled())
            {
                return chain.filter(exchange);
            }

            try
            {
                String rspStr = resolveBodyFromRequest(request);
                JSONObject obj = JSON.parseObject(rspStr);
                if(VALIDATE_LOGIN_URL.equals(request.getURI().getPath())) {
                    //判断是否跳过普通验证码验证
                    if(!SKIP_VERIFICATION_CODE_FLAG.equals(obj.getString(SKIP_VERIFICATION_CODE))) {
                        if (obj.getString(VERIFY_MODE).equals(PASSWORD_CODEMODE)) {
                            validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
                        }
                    }
                }else if(VALIDATE_REGISTER_URL.equals(request.getURI().getPath())){
                    //TODO: 注册时，校验手机号及验证码是否匹配
                }
            }
            catch (Exception e)
            {
                //设置UTF-8字符集
                String message =new String(e.getMessage().getBytes(StandardCharsets.UTF_8));
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), message);
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
    {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
